from manager import Manager
import logging
import os

from gevent import monkey
#monkey.patch_all()

manager = Manager()

def run_loop():
    import gevent
    import signal
    def routine():
        while True:
            gevent.sleep(1)

    gevent.signal(signal.SIGINT, gevent.kill)
    thread = gevent.spawn(routine)
    thread.join()

@manager.command
def run(inbox=None, part_inbox=None, outbox=None, part_outbox=None, data_dir=None):
    from file_sync_fod import FileSyncFOD, Config
    cfg = Config()
    if data_dir:
        cfg.data_dir = data_dir
    if inbox:
        cfg.inbox = inbox
    if part_inbox:
        cfg.part_inbox = part_inbox
    if outbox:
        cfg.outbox = outbox
    if part_outbox:
        cfg.part_outbox = part_outbox

    instance = FileSyncFOD(cfg)

    run_loop()

def is_lose_event_happened(lose_rate=0.0):
    import random
    d = random.uniform(0, 1)
    return d < lose_rate

@manager.command
def run_gatekeeper(from_dir='', to_dir='', lose_rate=0.0):
    import gevent
    import shutil
    def gatekeeper_routine(from_dir, to_dir):
        if os.path.exists(from_dir):
            for file_name in os.listdir(from_dir):
                try:
                    from_file_path = os.path.join(from_dir, file_name)
                    to_file_path = os.path.join(to_dir, file_name)
                    if is_lose_event_happened(lose_rate):
                        os.remove(from_file_path)
                        logging.info('lose file, removed %s' % from_file_path)
                    else:
                        shutil.move(from_file_path, to_file_path)
                        logging.info('moved %s to %s' % (from_file_path, to_file_path))
                except Exception as ex:
                    logging.error(ex)

    timer = gevent.get_hub().loop.timer(0.0, 0.1)
    timer.start(gatekeeper_routine, from_dir, to_dir)

    run_loop()

if __name__ == '__main__':
    manager.main()
